package cn.jxau.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;

import cn.jxau.bean.form.ModifyPwd;
import cn.jxau.bean.po.ArticleComment;
import cn.jxau.bean.po.User;
import cn.jxau.bean.vo.JsonResult;
import cn.jxau.service.UserService;
/**
 * 和普通用户相关的服务
 * @author licho
 *
 */
@Service
public class UserServiceImpl extends AbstractCommonService implements UserService {
	
	@Override
	public boolean userIsExist(String userName, String email) {
		int count=-1;
		if(userName!=null){
			if(email!=null)
				count=userMapper.queryUserExist(userName, email);//当两者都不为空时
			else
				count=userMapper.queryUserExist(userName, "");
		}else{
			if(email!=null)
				count=userMapper.queryUserExist("", email);
		}
			
		return count<=0 ? false :true;
	}
	@Override
	public List<User> getUserListByPage(Page<User> page) {
		List<User> list=userMapper.selectPage(page,new EntityWrapper<User>().orderBy("id"));
		return list;
	}
	
	@Override
	public boolean updateUserStatus(User user) {
		boolean flag=false;
		User u=userMapper.selectById(user.getId());
		if(u!=null){
			flag=userMapper.updateById(user)>0 ?true :false;
		}
		return flag;
	}
	@Override
	public boolean deleteByUserId(Long id) {
		boolean flag=false;
		int result=-1;
		try{
			result=userMapper.deleteById(id);
			flag=result>0 ?true:false;
		}catch(Exception e){}
		return flag;
	}
	
	@Override
	public boolean insertUser(User user) {
		boolean flag=false;
		int result=-1;
		try {
			result=userMapper.insert(user);
			flag=result>0 ?true:false;
			System.out.println("flag:"+flag);
		} catch (Exception e) {
			e.printStackTrace();
			return flag;
		}
		return flag;
	}
	@Override
	public User getUserByNameOrEmail(String login, String pwd) {
		User user = userMapper.getUserByNameOrEmail(login, pwd);
		if(user==null){
			return null;
		}
		return user.getExist() ? user:null;
	}
	@Override
	public User getUserByid(Long id) {
		// TODO Auto-generated method stub
		User user=userMapper.selectById(id);
		return user;
	}
	
	@Override
	public JsonResult modifyPwd(ModifyPwd pwd) {
		JsonResult result=new JsonResult();
		Long id=pwd.getId();
		System.out.println("接收到的pwd:"+pwd);
		User user=userMapper.selectById(id);//
		if(user.getPwd().equals(pwd.getPwd())){
			//判断原密码是否输入正确
			User u=new User();
			u.setId(id);
			u.setPwd(pwd.getNpwd());
			int nums=userMapper.updateById(u);
			if(nums>0){
				result.setStatus("200");
				result.setMsg("密码修改成功");
			}else{
				result.setStatus("500");
				result.setMsg("未知错误，密码修改失败");
			}
		}else{
			//原密码输入错误
			result.setStatus("500");
			result.setMsg("原密码输入错误");
		}
		return result;
	}
}

















